<template>
	<view class="publishDemand">
		<uni-forms ref="valiForm" :rules="rules" :modelValue="valiFormData">
			<view class="publishDemand-content">
				<view class="formLabel no-border uni-flex border-bottom"><text>发布标题</text>
					<uni-forms-item required name="name">
						<uni-easyinput class="my-input" v-model="valiFormData.name" placeholder="请输入标题"
							placeholderStyle='font-size:28rpx;' maxlength='50' />
					</uni-forms-item>
				</view>
				<view class="formLabel">
					<!-- 标题容器（border-bottom） -->
					<view class="uni-flex uni-justify-between uni-align-center "
						:class="tags.length>0?'':'border-bottom'">
						<!-- 原标题和选择按钮 -->
						<text>雇主需求<text class="red">*</text></text>
						<view class="select_service" @click="selectService">选择服务
							<uni-icons type="right" size="15" color="#666666"></uni-icons>
						</view>
					</view>
					<view class="labelBox uni-flex uni-flex-wrap" :class="{
					  'border-bottom': tags.length > 0,
					  'labelBox-padding': tags.length > 0
					}">
						<!-- 遍历tags数组，确保每个tag有id和name -->
						<view class="uni-flex uni-align-center tag-list" v-for="tag in tags" :key="tag.id">
							<text style="height: 60rpx; line-height: 60rpx">{{ tag.name }}</text>
							<image :src="`${$ImgBaseUrl}icon_menu_close.png`" mode="widthFix" @click="toggleTag(tag)" />
						</view>
					</view>
				</view>
				<view class="formLabel no-border-textarea uni-flex-column">
					<text>服务内容<text class="red">*</text></text>
					<view class="uni-flex-item">
						<uni-forms-item name="content">
							<!-- 新增容器包裹文本框和计数器 -->
							<view class="textarea-wrapper">
								<uni-easyinput type="textarea" v-model="valiFormData.content" maxlength="5000"
									placeholder="请描述您的服务内容，以便为您推荐更精准的服务人员。" placeholderStyle='font-size:28rpx;' />
								<view class="counter">{{ valiFormData.content.length }}/5000</view>
							</view>
						</uni-forms-item>
						<view class="robotBox uni-flex uni-align-center">
							<image :src="`${$ImgBaseUrl}robot.png`" mode="scaleToFill" class="robot" />
							<text class="robot-text">推荐使用平台服务标准</text>
						</view>
					</view>
				</view>
				<view class="formLabel"><text>服务时间</text>
					<uni-forms-item name="date">
						<view class="date-box">
							<uni-datetime-picker type="date" :clear-icon="false" v-model="startTime"
								placeholder='开始时间' />
							<view class="line">-</view>
							<uni-datetime-picker type="date" :clear-icon="false" v-model="endTime" placeholder='结束时间'
								placeholderStyle='font-size:28rpx;' />
						</view>
					</uni-forms-item>
				</view>
				<view class="formLabel no-border uni-flex border-bottom"><text>用工人数</text>
					<uni-forms-item name="peopleNumber">
						<uni-easyinput class="my-input" v-model="valiFormData.peopleNumber" type="number"
							placeholder="请输入您需要的人数" placeholderStyle='font-size:28rpx;' />
					</uni-forms-item>
				</view>
				<view class="formLabel no-border uni-flex border-bottom"><text>服务预算</text>
					<uni-icons type="help" size="20" class="help" color="#999999"></uni-icons>
					<uni-forms-item name="price">
						<uni-easyinput class="my-input" v-model="valiFormData.price" type="number" placeholder="请输入您的预算"
							placeholderStyle='font-size:28rpx;' />
					</uni-forms-item>
				</view>
				<view class="formLabel no-border-textarea uni-flex uni-justify-between border-bottom">
					<text>服务地址<text class="red">*</text></text>
					<view class="uni-flex address-containe">
						<uni-forms-item name="address">
							<uni-easyinput class="my-input" v-model="valiFormData.address" placeholder="请输入服务的详细地址"
								placeholderStyle='font-size:28rpx;' />
						</uni-forms-item>
						<view class="addressButton" @click="openAddress">地址簿</view>
					</view>
				</view>
				<view class="formLabel no-border uni-flex border-bottom  uni-align-center"><text>联系人</text>
					<uni-forms-item name="contacts">
						<uni-easyinput class="my-input" v-model="valiFormData.contacts" placeholder="请输入联系人"
							placeholderStyle='font-size:28rpx;' />
					</uni-forms-item>
				</view>
				<view class="formLabel no-border uni-flex ">
					<text>联系方式</text>
					<uni-forms-item name="phone">
						<uni-easyinput class="my-input" type="number" v-model="valiFormData.phone" placeholder="请输入联系方式"
							placeholderStyle='font-size:28rpx;' />
					</uni-forms-item>
					<text class="help-text" @click="showPhoneConfirm">使用当前手机号</text>
				</view>
			</view>
		</uni-forms>

		<view class="publishDemand-button" @click="submit('valiForm')">发布</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onUnmounted,
		watch,
		getCurrentInstance,
		onMounted
	} from "vue";
	import {
		addDemand,
		serviceInfo
	} from "@/api/publishDemand.js";
	// 响应式数据
	const isChecked = ref(false);
	const newLabel = ref("");
	const valiForm = ref();
	const addressItem = ref({});


	const eventChannel = getCurrentInstance().proxy.getOpenerEventChannel()

	// 定义开始和结束时间
	const startTime = ref('');
	const endTime = ref('');

	// 表单数据
	const valiFormData = reactive({
		name: "",
		content: "",
		// date: [], // 移除 date 字段
		startTime: "", // 新增：开始时间
		endTime: "", // 新增：结束时间
		peopleNumber: "",
		price: "",
		address: "",
		contacts: "",
		phone: "",
		addressId: "",
	});

	// 校验规则
	const rules = reactive({
		name: {
			rules: [{
				required: true,
				errorMessage: "",
			}, ],
		},
		content: {
			rules: [{
				required: true,
				errorMessage: "",
			}, ],
		},
	});

	// 标签数据
	const tags = ref([]);
	// 显示手机号确认弹窗
	const showPhoneConfirm = () => {
		try {
			// 从本地存储获取用户信息
			const userInfoStr = uni.getStorageSync('user_info');
			if (userInfoStr) {
				const userInfo = JSON.parse(userInfoStr);
				const userPhone = userInfo.phone;

				if (userPhone) {
					uni.showModal({
						title: '使用当前手机号',
						content: `是否使用手机号 ${userPhone} 作为联系方式？`,
						confirmText: '使用',
						cancelText: '取消',
						success: (res) => {
							if (res.confirm) {
								valiFormData.phone = userPhone;
							}
						}
					});
				} else {
					uni.showToast({
						icon: 'none',
						title: '未找到手机号信息'
					});
				}
			} else {
				uni.showToast({
					icon: 'none',
					title: '请先登录'
				});
			}
		} catch (e) {
			console.error('获取用户信息失败:', e);
			uni.showToast({
				icon: 'none',
				title: '获取信息失败'
			});
		}
	};
	onMounted(() => {
		// 监听服务项选择页发送的事件，接收选中的服务项
		eventChannel.on('acceptDataFromOpenedPage', (data) => {
			if (data.selectedServices && Array.isArray(data.selectedServices)) {
				// 更新本地标签列表
				tags.value = data.selectedServices
			}
		})
		eventChannel.on('sendDataToPageB', (data) => {
			// 修改数据查询详情接口
			if (data.initData.id) {
				serviceInfo({
					id: data.initData.id,
					typeId: data.initData.typeId
				}).then(res => {
					if (res.code === 200) {
						const serviceInfo = res.data.serviceInfo;
						valiFormData.name = serviceInfo.name;
						valiFormData.content = serviceInfo.content;
						// --- 修改点：将开始和结束时间分别赋值 ---
						startTime.value = serviceInfo.startTime || '';
						endTime.value = serviceInfo.endTime || '';
						valiFormData.peopleNumber = serviceInfo.peopleNumber;
						valiFormData.price = serviceInfo.price;
						valiFormData.address = serviceInfo.address;
						valiFormData.contacts = serviceInfo.contacts;
						valiFormData.phone = serviceInfo.phone;

						// --- 新增：处理雇主需求（labelNames）回显 ---
						if (serviceInfo.labelNames && Array.isArray(serviceInfo.labelNames)) {
							// 将 labelNames 数组转换为 tags 所需格式（id 可临时用索引或 name 代替）
							tags.value = serviceInfo.labelNames.map((name, index) => ({
								id: `temp_${index}_${name}`, // 生成临时唯一ID（避免重复）
								name: name, // 标签名称
								isCustom: false // 标记为非自定义标签（根据实际业务调整）
							}));
						}
					}

				})
			}
			console.log('收到PageA数据:', data)
		})
	})

	// 添加日期变化处理方法 - 此方法已不再需要，因为v-model已处理
	// const handleDateChange = (e) => {
	// 	console.log('日期选择:', e);
	// 	valiFormData.date = e || [];
	// };

	// 方法
	const onCheckChange = () => {
		isChecked.value = !isChecked.value;
	};

	const toggleTag = (tag) => {
		const index = tags.value.findIndex((t) => t.id === tag.id);
		if (index > -1) {
			tags.value.splice(index, 1); // 删除标签
			console.log("删除后tags数组:", tags.value); // 验证是否已移除
		} else {
			tags.value.push(tag);
		}
	};
	const selectService = () => {
		uni.navigateTo({
			url: "/pages/contract/addService",
			events: {
				acceptDataFromOpenedPage: (data) => {
					if (data.selectedServices && Array.isArray(data.selectedServices)) {
						tags.value = data.selectedServices;
						console.log("接收服务项数据:", tags.value);
					}
				}
			},
			success: (res) => {
				// 核心修复：传递当前最新的tags数据（删除后的数据）
				res.eventChannel.emit('acceptDataFromOpenerPage', {
					selectedServices: tags.value // 直接传递最新的tags数组
				});
			}
		});
	};
	const openAddress = () => {
		uni.navigateTo({
			url: "/pages/tabBars/serviceAddress/serviceAddress",
			events: {
				acceptDataAddress: (data) => {
					console.log(data);
					addressItem.value = data;
					valiFormData.contacts = data.contacts;
					valiFormData.phone = data.phone;
					valiFormData.address = data.provinceLive + data.cityLive + data.areaLive + data
						.address + data.doorNumber;
					valiFormData.addressId = data.id;
				},
			},
		});
	};

	const submit = (ref) => {
		// 原有校验逻辑保持不变
		if (valiFormData.name === "" || valiFormData.name === undefined) {
			return uni.showToast({
				icon: "none",
				title: "请输入标题"
			});
		}
		if (valiFormData.content === "" || valiFormData.content === undefined) {
			return uni.showToast({
				icon: "none",
				title: "请输入服务内容"
			});
		}
		if (valiFormData.address === "" || valiFormData.address === undefined) {
			return uni.showToast({
				icon: "none",
				title: "请选择服务地址"
			});
		}
		// 校验服务项是否选择（如果必填）
		if (tags.value.length === 0) {
			return uni.showToast({
				icon: "none",
				title: "请至少选择一个服务项"
			});
		}

		// --- 新增：提取服务项ID并拼接为categoryIds ---
		// 筛选系统服务项（非自定义）的serviceItemId或id
		const systemTagIds = tags.value
			.filter(tag => !tag.isCustom) // 排除自定义标签
			.map(tag => tag.serviceItemId || tag.id); // 取服务项ID（优先serviceItemId）

		// 用逗号拼接ID（如："1,2,3"）
		const categoryIds = systemTagIds.join(',');

		// 构造提交参数，加入categoryIds
		const params = {
			...valiFormData,
			startTime: startTime.value,
			endTime: endTime.value,
			categoryIds: categoryIds // 新增：服务项ID字符串
		};

		// 如果开始时间为空，移除 startTime 和 endTime（保持原有逻辑）
		if (!startTime.value) {
			delete params.startTime;
			delete params.endTime;
		}

		console.log("提交参数（含服务项ID）:", params);

		// 调用接口提交数据
		addDemand(params).then((res) => {
			if (res.code === 200) {
				uni.showToast({
					icon: "none",
					title: "发布成功"
				});
				eventChannel.emit('acceptDataFromPageB', {
					status: 'success'
				});
				uni.navigateBack();
			}
		});
	};

	// 防抖控制
	const debounceTimer = ref(null);
	const lastContent = ref("");
	const isTyping = ref(false);

	const TYPING_THRESHOLD = 300;
	const MIN_CONTENT_LENGTH = 5;
	const REQUEST_DELAY = 10000;

	watch(
		() => valiFormData.content,
		(newVal) => {
			clearTimeout(debounceTimer.value);
			isTyping.value = true;

			if (
				newVal.length - lastContent.value.length > 2 ||
				newVal.length < lastContent.value.length
			) {
				lastContent.value = newVal;
			}

			if (newVal.length >= MIN_CONTENT_LENGTH) {
				debounceTimer.value = setTimeout(() => {
					if (isTyping.value && newVal.length >= MIN_CONTENT_LENGTH) {
						isTyping.value = false;
						console.log("超时请求fetchRecommendations");
					}
				}, TYPING_THRESHOLD);
			}

			debounceTimer.value = setTimeout(() => {
				if (newVal.length >= MIN_CONTENT_LENGTH) {
					console.log("超时请求");
				}
			}, REQUEST_DELAY);
		}
	);

	onUnmounted(() => {
		clearTimeout(debounceTimer.value);
	});
</script>

<style lang="scss">
	.formLabel {
		.uni-forms-item {
			flex: 1;
			margin-bottom: 30rpx;
		}

		.uni-easyinput__content-textarea {
			background: #f6f6f6;
			margin: 0 !important;
			padding: 20rpx;
			height: 300rpx;
			border-radius: 10rpx;
		}
	}

	.no-border {
		.uni-forms-item__content .is-input-border {
			border: none !important;
			font-size: 28rpx;
			margin-top: 6rpx;
			text-align: right;
		}
	}

	.no-border-textarea {
		.uni-forms-item__content .is-input-border {
			border: none !important;
		}
	}
</style>

<style scoped lang="scss">
	.publishDemand {
		padding: 26rpx 24rpx 81rpx;
		background: #f5f5f5;
		min-height: calc(100vh - 26rpx);

		.publishDemand-content {
			background: #ffffff;
			border-radius: 20rpx;
			padding: 34rpx 26rpx 0 23rpx;
			margin-bottom: 40rpx;

			.no-border {
				margin-bottom: 29rpx;
			}

			.border-bottom {
				border-bottom: 1px solid #e2e2e2;
			}

			.formLabel {
				.help-text {
					font-weight: 400;
					font-size: 24rpx;
					color: #2f80ed;
					line-height: 33rpx;
					margin: 26rpx 0 0 24rpx;
				}

				.contentInput {
					background: #f6f6f6;
				}

				.address-containe {
					flex: 1;
					display: flex;
					justify-content: flex-end;
					margin-left: 20rpx;
				}

				.addressButton {
					flex-shrink: 0;
					height: 41rpx;
					padding-left: 24rpx;
					margin: 24rpx 0 0 0rpx;
					font-weight: 400;
					font-size: 28rpx;
					color: #333333;
					line-height: 40rpx;
					border-left: 1px solid #e2e2e2;
					margin-left: 24rpx;
				}

				.select_service {
					display: flex;
					color: #999999;
					font-size: 28rpx;
				}

				.help {
					margin: 0 16rpx;
					padding-top: 22rpx;
				}

				text {
					font-weight: 500;
					font-size: 28rpx;
					color: #303133;
					line-height: 80rpx;
				}

				.red {
					color: #dd524d;
				}

				.robotBox {
					margin: -10rpx 0 20rpx 0rpx;

					.robot {
						width: 29rpx;
						height: 24rpx;
						margin-right: 16rpx;
					}

					.robot-text {
						font-weight: 500;
						font-size: 24rpx;
						line-height: 24rpx;
						background-image: linear-gradient(27.827427004893497deg,
								#4d6dff 0%,
								#d688ff 100%);
						-webkit-background-clip: text;
						color: transparent;
					}
				}
			}

			.labelInputContainer {
				margin: 20rpx 0 42rpx;

				input {
					height: 70rpx;
					background: #f6f6f6;
					border-radius: 6rpx;
					padding: 0 20rpx;
					flex: 1;
				}

				.addLabelButton {
					padding: 0 22rpx;
					height: 70rpx;
					background: #2f80ed;
					border-radius: 6rpx;
					margin-left: 24rpx;
					font-weight: 400;
					font-size: 24rpx;
					color: #ffffff;
					line-height: 70rpx;
				}
			}

			.labelBox-padding {
				padding-bottom: 10rpx;
			}

			.labelBox {
				gap: 20rpx;

				.tag-list--selecte {
					background: #e5f0ff;
					color: #2f80ed;
				}

				.tag-list {
					padding: 0 19rpx;
					background: #f1f1f1;
					border-radius: 6rpx;
					font-weight: 400;
					font-size: 28rpx;
					color: #333333;

					image {
						width: 16rpx;
						height: 16rpx;
						margin-left: 20rpx;
					}
				}
			}
		}

		.publishDemand-footer {
			margin: 42rpx 0 86rpx;
			display: flex;

			.checkbox-label {
				margin-left: 16rpx;
				font-weight: 400;
				font-size: 28rpx;
				color: #999999;
				line-height: 40rpx;

				.blue_link {
					color: #2f80ed;
				}
			}
		}

		.publishDemand-button {
			width: 86%;
			height: 88rpx;
			background: #2f80ed;
			border-radius: 44rpx;
			text-align: center;
			font-weight: 600;
			font-size: 30rpx;
			color: #ffffff;
			line-height: 88rpx;
			margin: 0 auto;
		}
	}

	::v-deep .uni-date-editor {
		width: 300rpx;
	}

	::v-deep .uni-date-editor--x {
		height: 88rpx;
	}

	.date-box {
		display: flex;
		align-items: center;
		justify-content: space-between;

		.line {
			font-size: 28rpx;
			color: #999;
			font-weight: 400;
			margin-right: 20rpx;
			margin-left: 10rpx;
		}
	}

	::v-deep .uni-easyinput {
		margin-top: 15rpx;
	}

	// 文本框容器样式
	.textarea-wrapper {
		position: relative;
		width: 100%;
	}

	// 调整文本框内边距，避免文字被计数器遮挡
	::v-deep .uni-easyinput[type="textarea"] .uni-easyinput__content {
		padding-bottom: 40rpx !important;
		min-height: 200rpx;
	}

	.counter {
		position: absolute;
		right: 20rpx;
		bottom: 10rpx;
		text-align: right;
		font-size: 12px;
		color: #999;
		pointer-events: none;
	}
</style>